/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
import {ListNode} from "../datastructure/listNodeUse";

// 方法一：单调栈
export function nextLargerNodes(head: ListNode | null): number[] {
    const ans: number[] = [];
    // number[][] 因为这个number[]报错！！！！！
    // const stack: number[] = [];
    const stack: number[][] = [];
    let cur: ListNode | null = head;
    let idx: number = -1;
    while (cur) {
        ++idx;
        ans.push(0);
        // as number 报错
        while (stack.length && stack[stack.length-1][0] < cur.val) {
            ans[stack.pop()[1]] = cur.val;
        }
        stack.push([cur.val, idx]);
        cur = cur.next;
    }
    const size: number = ans.length;
    const arr: number[] = new Array(size);
    for (let i=0; i<size; ++i) {
        arr[i] = ans[i];
    }
    return arr;
}

export function nextLargerNodesTwo(head: ListNode | null): number[] {
    const nums: number[] = [];
    while (head) {
        nums.push(head.val);
        head = head.next;
    }
    const stk: number[] = [];
    const n = nums.length;
    const ans: number[] = new Array(n).fill(0);
    for (let i = n - 1; ~i; --i) {
        while (stk.length && stk[stk.length - 1] <= nums[i]) {
            stk.pop();
        }
        ans[i] = stk.length ? stk[stk.length - 1] : 0;
        stk.push(nums[i]);
    }
    return ans;
}
